
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import { Form, Input, Button, message, Tabs } from 'antd';
import { formRequire, formMobile, formMax } from '../../common/rule';
import { register, login, articleUrl } from '../../common/constant';
import { tokenData } from '../../common/fetch';
import styles from './index.module.css';

const { Item: FormItem } = Form;
const { TabPane } = Tabs;

function Login() {

  const router = useHistory();

  // 1 => 登陆， 2 => 注册
  const [loginState, setLoginState] = useState(1);
  const [form] = Form.useForm();

  const onReset = () => form.resetFields();

  const onFinish = values => {
    const { password } = values;
    (loginState === 1 ? login : register)({ ...values, password: window.btoa(password) })
      .then(res => {
        if (res.result) {
          message.success(loginState === 1 ? '登录成功' : '注册成功');
          tokenData.Authorization = res.result.token;
          router.push(articleUrl);
        } else {
          message.error(res.message);
          // onReset()
        }
      })
  }

  const onFinishFailed = error => {
    console.error(error)
    message.error('请输入有效的手机号和密码')
  }

  return (
    <>
      <Tabs
        defaultActiveKey={loginState}
        className={styles.login}
        onChange={key => setLoginState(+key)}
      >
        {['登录', '注册'].map((item, i) => (
          <TabPane tab={item} key={i + 1} />
        ))}
      </Tabs>
      <Form
        name='userForm'
        className={styles.form}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        form={form}
      >
        <FormItem
          label='手机号'
          name='mobile'
          rules={formMobile}
        >
          <Input placeholder='请输入手机号' />
        </FormItem>
        <FormItem
          label='密码'
          name='password'
          rules={formRequire}
        >
          <Input.Password placeholder='请输入密码' />
        </FormItem>
        {loginState !== 1 && (
          <FormItem
            label='用户名'
            name='username'
            rules={formMax(20)}
          >
            <Input placeholder='请输入用户名' />
          </FormItem>
        )}
        <div className={styles.submit}>
          <Button type='primary' htmlType='submit'>{loginState === 1 ? '登录' : '注册'}</Button>
        </div>
      </Form>
    </>
  );
}

export default Login
